package dao.purchasing;

import dao.BaseDaoHibernate;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import model.purchasing.TorderDetail;
import model.purchasing.TorderMst;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

@Repository
public class TorderDao extends BaseDaoHibernate<TorderMst>{
    
    public long saveData(TorderMst domain) {
        return insertTemporary(domain);
    }
        
    public long insertTemporary(TorderMst domain) {
        Session session = sessionFactory.openSession();
        long entryId = 0;
        try {
            session.beginTransaction();
                      
            sessionFactory.getCurrentSession().save(domain);
            entryId = domain.getId();  
            
            for (TorderDetail detail : domain.getTorderDetails()) {
                detail.getId().setId(entryId);
            }
            
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            session.getTransaction().rollback(); 
            entryId=0;
            java.util.logging.Logger.getLogger(TorderDao.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            if (session != null) { session.close();}
            return entryId;
        }
    }
    
    public boolean manageOder(long id) {
        Session session = sessionFactory.openSession();
        boolean sukses=false;
        try {
            session.beginTransaction();
            
            CallableStatement sp = session.connection().prepareCall("{call purchasing.manage_order (?)}");
            sp.setLong(1, id);
            sp.executeUpdate();
            
            session.getTransaction().commit();
            sukses=true;
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(TorderDao.class.getName()).log(Level.SEVERE, null, ex);
            session.getTransaction().rollback(); 
            sukses=false;
        } finally {
            if (session != null) { session.close();}
            return sukses;
        }
    }
}
